package com.anotherrobbo.armedia.server.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.net.ServerSocketFactory;

import com.anotherrobbo.armedia.engine.PlayerEngine;
import com.anotherrobbo.armedia.server.AbstractReader;

public class SocketReader extends AbstractReader {
	
	private int port;

	public SocketReader(int port, PlayerEngine engine) {
		super("SocketReader", engine);
		this.port = port;
	}

	@Override
	protected void read() {
		try {
			ServerSocket socket = ServerSocketFactory.getDefault().createServerSocket(port);
			
			boolean connect = true;
			while (connect) {
				Socket client;
				try {
					log.info("Awaiting connection on port: " + port + "...");
					client = socket.accept();
					BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
					PrintWriter writer = new PrintWriter(client.getOutputStream(), true);
					log.info("Connection established");
					writer.println("Connection established");
					
					try {
						String line = reader.readLine();
						while (connect && line != null) {
							connect = actionInput(line);
							line = connect ? reader.readLine() : null;
						}
						reader.close();
						writer.close();
						client.close();
						connect = true;
					} catch (IOException ioe) {
						log.error("IOException thrown: ", ioe);
					}					
				} catch (IOException ioe) {
					log.error("IOException thrown during accept: ", ioe);
					break;
				}				
			}
			socket.close();
		} catch (IOException ioe) {
			log.error("IOException thrown during socket creation: ", ioe);
		}
	}
	
}
